package com.climber.android.commonres.ui

import android.annotation.SuppressLint
import android.graphics.Paint
import android.text.TextUtils
import android.util.Log
import android.view.WindowManager
import com.climber.android.commonres.R
import com.climber.android.commonres.widget.CircleBarView
import com.climber.android.commonsdk.app.AppConstants
import io.ganguo.library.klog.KLog
import io.ganguo.library.mvp.Config
import io.ganguo.library.mvp.ui.mvp.IPresenter
import io.ganguo.library.mvp.ui.mvp.di.component.AppComponent
import io.ganguo.library.mvp.util.AppUtils
import io.ganguo.library.mvp.util.BitmapUtils
import io.ganguo.library.mvp.util.ToastHelper
import io.ganguo.library.mvp.util.UIUtils
import io.ganguo.library.rxdownload.RxDownload
import io.ganguo.library.rxdownload.entity.DownloadEvent
import io.ganguo.library.rxdownload.entity.DownloadFlag
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.com_activity_download_file.*
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * Created by Mikes at 2020-04-21 17:19
 */
class DownloadFileDialogActivity : BaseMVPActivity<IPresenter>() {
    companion object {
        val TIME_FORMAT = SimpleDateFormat("yyyy_MM_dd_HH_mm_ss")
    }

    private val downloadUrl: String by lazy {
        intent.getStringExtra("downloadUrl") ?: ""
    }

    private var downloadEventFlag = -1
    private var downloadDisposable: Disposable? = null
    private var downloadStatusDisposable: Disposable? = null

    private val rxDownload by lazy {
        RxDownload.getInstance(AppUtils.getApp())
                .defaultSavePath(Config.getAppFilesRootPath() + "video")
                .maxThread(3)
                .maxRetryCount(2)
                .maxDownloadNumber(2)
    }

    override fun setupActivityComponent(appComponent: AppComponent) {
    }

    override fun getLayoutResourceId(): Int = R.layout.com_activity_download_file

    override fun initView() {
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
    }

    @SuppressLint("AutoDispose")
    override fun initListener() {
        downloadProgressBar.setTextView(progressLabel)
        downloadProgressBar.setOnAnimationListener(object : CircleBarView.OnAnimationListener {
            override fun howToChangeText(updateNum: Float, maxNum: Float): String {
                val decimalFormat = DecimalFormat("0.00")
                return "已下载\n" + decimalFormat.format(updateNum / maxNum * 100) + "%"
            }

            override fun howTiChangeProgressColor(paint: Paint, updateNum: Float, maxNum: Float) {
            }
        })

        downloadProgressBar.setOnClickListener {
            when (downloadEventFlag) {
                DownloadFlag.STARTED -> {
                    // 点击暂停下载
//                    rxDownload.pauseServiceDownload(downloadUrl).subscribe()
                }
                DownloadFlag.PAUSED -> {
                    // 点击恢复下载
//                    downloadDisposable?.dispose()
//                    downloadDisposable = rxDownload.serviceDownload(downloadUrl).subscribe()
                }
                DownloadFlag.WAITING -> {
                }
                DownloadFlag.COMPLETED -> {
                }
                DownloadFlag.FAILED -> {
                    // 点击重新下载
                    startDownloadFile(downloadUrl)
                }
                else -> {
                }
            }
        }
    }

    override fun initData() {
        startDownloadFile(downloadUrl)
    }

    override fun onBackPressed() {
        downloadDisposable?.dispose()
        downloadStatusDisposable?.dispose()

        finish()
        overridePendingTransition(0, R.anim.cbase__slide_out_to_bottom)
    }

    @SuppressLint("AutoDispose")
    private fun startDownloadFile(downloadLink: String) {
        if (downloadLink.isEmpty()) return

        downloadDisposable?.dispose()
        downloadStatusDisposable?.dispose()

        downloadDisposable = rxDownload.serviceDownload(downloadLink, getFormatFileName(downloadUrl))
                .subscribe()

        downloadStatusDisposable = rxDownload
                .receiveDownloadStatus(downloadLink)
                .sample(1L, TimeUnit.SECONDS, true)
                .doOnSubscribe {
                    updateUIWithDownloadEvent(DownloadEvent().apply {
                        flag = DownloadFlag.WAITING
                    })
                }
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ downloadEvent ->
                    updateUIWithDownloadEvent(downloadEvent)
                    KLog.d(AppConstants.LOG_TAG, " flag :" + downloadEvent.flag + ", downloadStatus : " + downloadEvent.downloadStatus.percent + ", error :" + downloadEvent.error)

                    if (downloadEvent.flag == DownloadFlag.COMPLETED) {
                        rxDownload.getDownloadRecord(downloadLink)
                                .subscribe { downloadRecord ->
                                    Log.d(AppConstants.LOG_TAG, "notificationTitle :" + downloadRecord.saveName + "; savePath : " + downloadRecord.savePath)
                                    ToastHelper.toastMessage("视频已保存")
                                    BitmapUtils.notifyMediaScanner(this@DownloadFileDialogActivity, downloadRecord.savePath)
                                }
                    }
                }, { error ->
                    Log.e(AppConstants.LOG_TAG, "", error)

                    updateUIWithDownloadEvent(DownloadEvent().apply {
                        flag = DownloadFlag.FAILED
                    })
                })
    }

    private fun getFormatFileName(url: String): String {
        return TIME_FORMAT.format(Date()) + "." + getFileExtensionFromUrl(url)
    }

    private fun getFileExtensionFromUrl(urlParam: String): String {
        var url = urlParam
        if (!TextUtils.isEmpty(url)) {
            val fragment = url.lastIndexOf('#')
            if (fragment > 0) {
                url = url.substring(0, fragment)
            }

            val query = url.lastIndexOf('?')
            if (query > 0) {
                url = url.substring(0, query)
            }

            val filenamePos = url.lastIndexOf('/')
            val filename = if (0 <= filenamePos) url.substring(filenamePos + 1) else url

            if (!TextUtils.isEmpty(filename)) {
                val dotPos = filename.lastIndexOf('.')
                if (0 <= dotPos) {
                    return filename.substring(dotPos + 1)
                }
            }
        }

        return ""
    }

    private fun updateUIWithDownloadEvent(downloadEvent: DownloadEvent) {
        downloadEventFlag = downloadEvent.flag
        when (downloadEvent.flag) {
            DownloadFlag.STARTED -> {
                progressLabel.setTextColor(UIUtils.getColor(R.color.common_green))
                downloadProgressBar.setProgress(downloadEvent.downloadStatus.downloadSize.toFloat(), downloadEvent.downloadStatus.totalSize.toFloat())
            }
            DownloadFlag.PAUSED -> {
                progressLabel.text = "已暂停"
                progressLabel.setTextColor(UIUtils.getColor(R.color.common_text_secondary))
            }
            DownloadFlag.WAITING -> {
                progressLabel.text = "等待中..."
                progressLabel.setTextColor(UIUtils.getColor(R.color.common_text_secondary))
            }
            DownloadFlag.COMPLETED -> {
                progressLabel.text = "下载完毕"
                progressLabel.setTextColor(UIUtils.getColor(R.color.common_green))
                downloadProgressBar.setProgress(100F, 100F)
            }
            DownloadFlag.FAILED -> {
                progressLabel.text = "下载出错"
                progressLabel.setTextColor(UIUtils.getColor(R.color.common_warning_red))
            }
            else -> {
            }
        }
    }
}